package com.haochang.chunkvod.view.vod.listView.swipemenulistview;

import java.util.List;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**滑动后右侧显示的布局
 *     @author Yangjie
 *     className SwipeMenuView
 *     created at  2016/10/20  17:53
 */
public class SwipeMenuView extends LinearLayout implements OnClickListener
{
	private SwipeMenuLayout mLayout;
	private SwipeMenu mMenu;
	private OnSwipeItemClickListener onItemClickListener;
	private int position;

	public int getPosition()
	{
		return position;
	}

	public void setPosition(int position)
	{
		this.position = position;
	}

	public SwipeMenuView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public SwipeMenuView(SwipeMenu menu)
	{
		super(menu.getContext());
		mMenu = menu;
		List<SwipeMenuItem> items = menu.getMenuItems();
		int id = 0;
		for (SwipeMenuItem item : items)
		{
			addItem(item, id++);
		}
	}

	private void addItem(SwipeMenuItem item, int id)
	{
		LayoutParams params = new LayoutParams(item.getWidth(), LayoutParams.MATCH_PARENT);
		LinearLayout parent = new LinearLayout(getContext());
		parent.setId(id);
		parent.setGravity(Gravity.CENTER);
		parent.setOrientation(LinearLayout.VERTICAL);
		parent.setLayoutParams(params);
		parent.setBackgroundDrawable(item.getBackground());
		parent.setOnClickListener(this);
		addView(parent);

		if (item.getIcon() != null)
		{
			parent.addView(createIcon(item));
		}
		if (!TextUtils.isEmpty(item.getTitle()))
		{
			parent.addView(createTitle(item));
		}

	}

	private ImageView createIcon(SwipeMenuItem item)
	{
		ImageView iv = new ImageView(getContext());
		iv.setImageDrawable(item.getIcon());
		return iv;
	}

	private TextView createTitle(SwipeMenuItem item)
	{
		TextView tv = new TextView(getContext());
		tv.setText(item.getTitle());
		tv.setGravity(Gravity.CENTER);
		tv.setTextSize( TypedValue.COMPLEX_UNIT_SP,item.getTitleSize());//以sp为单位
		tv.setTextColor(item.getTitleColor());
		return tv;
	}

	@Override
	public void onClick(View v)
	{
		if (onItemClickListener != null && mLayout.isOpen())
		{
			onItemClickListener.onItemClick(this, mMenu, v.getId());
		}
	}

	public void setOnSwipeItemClickListener(OnSwipeItemClickListener onItemClickListener)
	{
		this.onItemClickListener = onItemClickListener;
	}

	public void setLayout(SwipeMenuLayout mLayout)
	{
		this.mLayout = mLayout;
	}

	public interface OnSwipeItemClickListener
	{
		void onItemClick(SwipeMenuView view, SwipeMenu menu, int index);
	}
}
